package com.gsy.aop;

import cn.hutool.core.date.DateUtil;
import com.gsy.utils.RedisCacheUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 参数验证
 */
@Aspect
@Component
@SuppressWarnings("static-method")
public class ResubmitDataAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(ResubmitDataAspect.class);



    @Pointcut("@annotation(com.gsy.aop.annotation.ResubmitData)")
    public void valid() {
    }

    /**
     * 验证处理
     *
     * @param joinPoint
     * @throws Exception
     */
    @Before("valid()")
    public void validProcess(JoinPoint joinPoint) throws Exception {

        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String requestURI = httpServletRequest.getRequestURI();//拿到请求的url
        String token = httpServletRequest.getHeader("Authorization");//拿到请求头

        //token存在才校验
        if (StringUtils.isNotEmpty(token)){
            //redis有数据表示这段时间有重复提交
            if (RedisCacheUtils.hasKey(requestURI+"_"+token)){
                throw new RuntimeException("请勿重复提交！！！");
            }
            //区间内暂无访问数据存入redis
            RedisCacheUtils.putCache(requestURI+"_"+token, DateUtil.date().toMsStr(),2);

        }

    }


}
